package com.knowledge.graph.utils;

import com.knowledge.graph.exception.FileException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author jiwenlong
 * @version 1.0
 * @description: 处理文件操作的工具类
 * @date 2023/11/14 22:13
 */
public class FileUtils {

    public static File addFile(String directory, MultipartFile multipartFile) {
        File preDirectory = new File(directory);
        if (!preDirectory.exists()) {
            preDirectory.mkdirs();
        }
        File file = new File(preDirectory, multipartFile.getOriginalFilename());
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static void deleteFile(File file) {
        if (file.isDirectory())
            try {
                File[] fileList = file.listFiles();
                for (File videoFile : fileList)
                    videoFile.delete();
                file.delete();
            } catch (Exception e) {
                throw new FileException("文件夹删除失败");
            }
        else {
            try {
                file.delete();
            }catch (Exception e){
                throw new FileException("文件删除失败");
            }
        }
    }

    public static String ImageToBase64(String filePath) throws IOException {
        File file = ResourceUtils.getFile(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        //使用IO流将其转换为字节数组
        byte[] bytes = IOUtils.toByteArray(fileInputStream);
        //将字节转换为base64
        String encodeBase64 = Base64.encodeBase64String(bytes);
        //关闭IO流
        fileInputStream.close();
        return encodeBase64;
    }
}
